﻿using IDEAMS.model;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IDEAMS.core.deviceClient
{
    public class DeviceClientManager
    {
        private readonly object locker = new object();
        private static ILog logger = LogManager.GetLogger(typeof(DeviceClientManager));

        public Dictionary<string, DeviceClient> clientList;

        public DeviceClientManager()
        {
            clientList = new Dictionary<string, DeviceClient>();
        }

        private DeviceClient Create(DeviceInfo deviceInfo)
        {
            DeviceClient client = new DeviceClient(deviceInfo.ip, deviceInfo.port);
            return client;
        }

        public int Load(DeviceInfoCollection devices)
        {
            int rn = 0;
            devices.ForEach(v =>
            {
                DeviceClient client = Create(v);
                if (client == null)
                {
                    logger.ErrorFormat("设备接收器[{0}]创建失败", v.serialNo);
                    return false; //继续loop
                }
                clientList.Add(v.serialNo, client);
                return false;
            });

            return rn;
        }

        public int Add(string key, DeviceClient client)
        {
            int rn = 0;
            lock (locker)
            {
                try
                {
                    clientList.Add(key, client);
                }
                catch (Exception)
                {
                    rn = -1;
                }
            }
            return rn;
        }

        public int Delete(string key)
        {
            int rn = 0;
            try
            {
                if (clientList.ContainsKey(key))
                {
                    clientList.Remove(key);
                }
            }
            catch (Exception)
            {
                rn = -1;
            }
            return rn;
        }

        public DeviceClient Find(string key)
        {
            DeviceClient rn = null;
            try
            {
                if (clientList.ContainsKey(key))
                {
                    rn = clientList[key];
                }
                return rn;
            }
            catch (Exception)
            {
                rn = null;
            }
            return rn;
        }

        public void Clear()
        {
            try
            {
                clientList.Clear();
            }
            catch (Exception)
            {

            }
        }
    }
}
